package grib2handler.grib.netcdf;

import java.io.File;
import java.util.Collections;
import java.util.List;

import grib2handler.grib.GribPoolDownTask;
import grib2handler.util.FileUtil;
import grib2handler.util.PropertiesUtil;

/**
 * grib数据解析成可读文本
 * @author charlie
 *
 */
public class GribPass {
	/**
	 * grib目录
	 */
	public static String in = GribPoolDownTask.getGribOutFile();
	/**
	 * grib解压后目录
	 */
	public static final String out = "gribexport";
	/**
	 * 发布时间
	 */
	private String time = "2014032500";
	/**
	 * 发布机构
	 */
	private String agency = "uk";
	/**
	 * 模块
	 */
	private String model = "avn";
	
	private String pathIn = "";
	private String pathOut = "";
	
	public GribPass(String time, String agency, String model) {
		super();
		this.time = time;
		this.agency = agency;
		this.model = model;
		String temp = "/" + this.time + "/" + this.agency + "/" + this.model;
		pathIn = in + temp;
		pathOut = out + temp;
	}
	
	/**
	 * 解析文件夹下所有文件
	 */
	public void dopass() {
		List<File> files = FileUtil.readPathFiles(pathIn, FileUtil.GRIB2);
		for (File file : files) {
			String name = file.getName().replace("." + FileUtil.GRIB2, "");
			dopass(name);
		}
	} 
	/**
	 * 删除旧缓存
	 */
	public static void delOldTemp() {
		List<File> filesIn = FileUtil.readPathFiles(in, null);
		int tempSize = PropertiesUtil.getConfig().getInt("tempSize", 40);
		Collections.sort(filesIn);
		if(filesIn.size()> tempSize) {
			for (int i = 0; i < filesIn.size() - tempSize; i++) {
				
				FileUtil.delPath(filesIn.get(i).getAbsolutePath());
			}
		}
		List<File> filesOut = FileUtil.readPathFiles(out, null);
		Collections.sort(filesOut);
		if(filesOut.size()> tempSize) {
			for (int i = 0; i < filesOut.size() - tempSize; i++) {
				FileUtil.delPath(filesOut.get(i).getAbsolutePath());
			}
		}
	}
	
	/**
	 * 解析下载好的某一个文件
	 * @param fileNameNoExt  没有扩展后缀文件名
	 * @return
	 */
	public boolean dopass(String fileNameNoExt) {
		File f = new File(pathIn + "/" + fileNameNoExt + "." + FileUtil.GRIB2 + ".KWBC");
		if(f.exists()) {
			try {
				NetcdfDump.getinstence().dump(f, pathOut + "/" + fileNameNoExt);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		NetcdfDump.getinstence().dump(new File("C:/svnnew/Meteorology/trunk/src/Skymeteo/SkymeteoProcessor/HHIB10EGRR061200"), 
//				"d:" + "/" + "xxx/");
		
		List<File> files = FileUtil.readPathFiles("D:/rtx/xujialei/grib/", null);
		for (File file : files) {
			NetcdfDump.getinstence().dump(file, "D:/rtx/xujialei/grib/xxx" + file.getName() + "/");
		}
	}

}
